/**
 * @(#)com.framework.web.wechat.controller.WeChatGoodsController
 *
 * Copyright (c) 2014-2018 一抹风光
 *
 * DESC:
 *
 */
package com.framework.web.wechat.controller;

import com.framework.core.domain.SessionVo;
import com.framework.core.util.DateUtils;
import com.framework.core.util.Persistence;
import com.framework.core.util.StringsToListUtil;
import com.framework.web.bus.domain.*;
import com.framework.web.bus.service.*;
import com.framework.web.common.domain.BusinessConstants;
import com.framework.web.common.domain.Constants;
import com.framework.web.wechat.service.WeChatCartService;
import com.framework.web.wechat.domain.WeChatRequest;
import com.framework.web.wechat.domain.WeChatResInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 购物车相关功能
 *
 * @author fusf
 * @version 1.0  2016/9/11
 */
@Controller
@RequestMapping("/weChat/cart")
public class WeChatCartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private WeChatCartService weChatCartService;

    @Autowired
    private OrderItemInfoService orderItemInfoService;

    @Autowired
    private GoodsInfoService goodsInfoService;


    /**
     * 加入购物车
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goodsAdd", method = RequestMethod.GET)
    @ResponseBody
    public Object addCart(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userGuid 找到userId
        //根据userId和goodsId查询是否存在
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        String userId = sessionVo.getUserId();
        Cart cart = cartService.findByUserIdAndGoodsId(userId, requestInfo.getGoodsId());
        if (cart == null) {
            cart = new Cart();
            cart.setUserId(userId);
            cart.setGoodsId(requestInfo.getGoodsId());
            cart.setCount(requestInfo.getNumber());
            cart.setCreateTime(new Date());
            cart.setCreateBy(userId);
            cart.setCreateName(sessionVo.getUserName());

        } else {
            cart.setCount(cart.getCount() + requestInfo.getNumber());
            cart.setUpdateTime(new Date());
            cart.setUpdateBy(sessionVo.getUserId());
            cart.setUpdateName(sessionVo.getUserName());
        }
        cartService.save(cart);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }

    /**
     * 购物车删除
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goodsDelete", method = RequestMethod.GET)
    @ResponseBody
    public Object deleteCart(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userId和goodsId查询是否存在
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        String userId = sessionVo.getUserId();
        Integer number = requestInfo.getNumber();
        String goodsId = requestInfo.getGoodsIds();//商品ID列表
        String[] array = goodsId.split(",");

        if (number == 0) {//0表示删除商品
            for (String gid : array) {
                Cart cart = cartService.findByUserIdAndGoodsId(userId, gid);
                cartService.delete(cart.getId());
            }
        } else if (number == 1) { //1表示减1
            Cart cart = cartService.findByUserIdAndGoodsId(userId, goodsId);
            Integer count = cart.getCount();
            if (count == 1) {
                cartService.delete(cart.getId());
            } else {
                cart.setCount(count - 1);
                cart.setUpdateTime(new Date());
                cart.setUpdateBy(sessionVo.getUserId());
                cart.setUpdateName(sessionVo.getUserName());
                cartService.save(cart);
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }

    /**
     * 购物车列表
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getCartList", method = RequestMethod.GET)
    @ResponseBody
    public Object getGoodlist(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userId和goodsId查询是否存在
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        String userId = sessionVo.getUserId();
        Map<String, Object> map = new HashMap<>();
        List<Cart> cartList = cartService.findByUserId(userId);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        //购物车列表
        for (Cart cart : cartList) {
            Map<String, Object> map_object = new HashMap<>();
            GoodsInfo goodsInfo = cart.getGoodsInfo();

            map_object.put("goodsId", goodsInfo.getId());//商品Id
            map_object.put("imageSmall", Persistence.getValue(Constants.FILEIP) + StringsToListUtil.toStringList(goodsInfo.getImg(), "@").get(0)); //商品图片
            map_object.put("price", goodsInfo.getPrice());//当前价格
            map_object.put("preferentical", goodsInfo.getCurrentPrice());//优惠价格
            map_object.put("freightPrice", "0");//运费价格
            map_object.put("freightFree", goodsInfo.getIsPost());//0免运费 1 不免运费
            if (goodsInfo.getIsPost() == 0) {
                map_object.put("postDescription", goodsInfo.getPostDesc());//快递描述
            } else {
                map_object.put("postDescription", "");
            }
            map_object.put("shopName", Persistence.getValue(Constants.SHOP_NAME));//店铺名称
            //map_object.put("shopDescription", "正宗的阳澄湖大闸蟹");//店铺描述
            map_object.put("buyers", goodsInfo.getBuyers());//购买人数
            map_object.put("salesNumber", goodsInfo.getSalesVolume());//销量
            map_object.put("goodsNumber", cart.getCount());// 购买数量
            mapList.add(map_object);
        }
        map.put("infoList", mapList);
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }


    /**
     * 下订单
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goodsOrder", method = RequestMethod.GET)
    @ResponseBody
    public Object goodsOrder(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userId和goodsId查询是否存在
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        //下订单
        String orderId = weChatCartService.createOrder(requestInfo, sessionVo);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", orderId);
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }

    /**
     * 取消订单
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goodsCancelOrder", method = RequestMethod.GET)
    @ResponseBody
    public Object goodsCancelOrder(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userId和goodsId查询是否存在
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        String orderId = requestInfo.getOrderId();
        Order order = orderService.findById(orderId);
        if (order != null) {
            order.setOrderStatus(BusinessConstants.ORDER_STATUS.INVALID);//订单取消
            order.setUpdateTime(new Date());//更新时间
            order.setUpdateBy(sessionVo.getUserId());
            order.setUpdateName(sessionVo.getUserName());
            orderService.save(order);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }


    /**
     * 订单列表列表
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goodsOrderList", method = RequestMethod.GET)
    @ResponseBody
    public Object getOrderlist(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userId和goodsId查询是否存在
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        String userId = sessionVo.getUserId();
        Map<String, Object> map = new HashMap<>();
        Integer orderType = requestInfo.getOrderType() - 1;
        List<Order> orderList = orderService.findByOrderStatusAndUserId(orderType, userId);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        //订单列表
        for (Order order : orderList) {
            Map<String, Object> map_object = new HashMap<>();
            map_object.put("orderId", order.getId());//订单ID
            map_object.put("orderTime", DateUtils.formateDate(order.getCreateTime()));//订单创建时间
            map_object.put("buyTime", DateUtils.formateDate(order.getBuyTime()));//订单付款时间
            map_object.put("customerMessage", order.getBuyerMsg());//客户留言
            map_object.put("orderNumber", order.getId());//订单编号
            map_object.put("allPrice", order.getTotalAmount());//总价
            map_object.put("shopName", Persistence.getValue(Constants.SHOP_NAME));//店铺名称
            List<OrderItemInfo> orderItemInfoList = orderItemInfoService.findByOrderId(order.getId());
            if (orderItemInfoList != null && orderItemInfoList.size() > 0) {
                OrderItemInfo orderItemInfo = orderItemInfoList.get(0);
                GoodsInfo goodsInfo = goodsInfoService.findById(orderItemInfo.getGoodsId());
                map_object.put("imageSmall", Persistence.getValue(Constants.FILEIP) + StringsToListUtil.getFistImage(StringsToListUtil.getFistImage(orderItemInfo.getGoodsSmImg()), "@"));//小图 TODO
                map_object.put("iteamsNumber", orderItemInfo.getQuantities());//购买商品的种类数量
                map_object.put("description", orderItemInfo.getGoodsDesc());//第一个商品描述
                map_object.put("freightFree", goodsInfo.getIsPost());//是否包邮
                if (goodsInfo.getIsPost() == 0) {
                    map_object.put("postDescription", goodsInfo.getPostDesc());//快递描述
                } else {
                    map_object.put("postDescription", "");
                }

            }
            List<Map<String, Object>> orderItemList_map = new ArrayList<Map<String, Object>>();
            for (OrderItemInfo orderItemInfo : orderItemInfoList) {
                Map<String, Object> orderItemMap = new HashMap<>();
                GoodsInfo goodsInfo = goodsInfoService.findById(orderItemInfo.getGoodsId());
                orderItemMap.put("goodsId", orderItemInfo.getGoodsId());//商品ID
                orderItemMap.put("imageSmall", Persistence.getValue(Constants.FILEIP) + StringsToListUtil.getFistImage(StringsToListUtil.getFistImage(orderItemInfo.getGoodsSmImg()), "@"));//小图 TODO
                orderItemMap.put("price", orderItemInfo.getCurrPrice());//售价
                orderItemMap.put("goodsNumber", orderItemInfo.getQuantities());//购买数量
                orderItemMap.put("description", orderItemInfo.getGoodsDesc());//商品描述
                orderItemMap.put("freightPrice", "0");//TODO
                orderItemMap.put("freightFree", goodsInfo.getIsPost());//是否包邮
                if (goodsInfo.getIsPost() == 0) {
                    orderItemMap.put("postDescription", goodsInfo.getPostDesc());//快递描述
                } else {
                    orderItemMap.put("postDescription", "");
                }
                orderItemMap.put("shopName", Persistence.getValue(Constants.SHOP_NAME));//店铺名称
                orderItemMap.put("buyers", goodsInfo.getBuyers());//购买人数
                orderItemMap.put("salesNumber", goodsInfo.getSalesVolume());//销量
                orderItemList_map.add(orderItemMap);
            }
            map_object.put("goodsList", orderItemList_map);
            mapList.add(map_object);
        }
        map.put("infoList", mapList);
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }


    /**
     * 订单付款
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/payment", method = RequestMethod.GET)
    @ResponseBody
    public Object paymentOrder(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        //根据userId和goodsId查询是否存在
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        String orderId = requestInfo.getOrderId();
        Double actualPay = requestInfo.getActualPay();
        Double shoudlePay = requestInfo.getShoudlePay();
        if (orderId != null) {
            orderService.payOrder(orderId,actualPay,shoudlePay);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }


}
